package de.haw.vs.appcontext;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;

public class DynamicalObjectInputStream extends ObjectInputStream {

	private String nameOfDynamicalClass;
	private final byte[] classBytes;

	public DynamicalObjectInputStream(String nameOfDynamicalClass, byte[] classBytes, byte[] externalization) throws IOException {
		super(new ByteArrayInputStream(externalization));
		this.nameOfDynamicalClass = nameOfDynamicalClass;
		this.classBytes = classBytes;
	}

	/**
	 * @see DynamicalClassLoader#defineClassMy(String, byte[])
	 */
	@Override
	protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
		if (desc.getName().equals(nameOfDynamicalClass)) {
			// damit wird sichergestellt, dass der neu erzeugte object zu keinem Konflikt fuehrt (LinkageError)
			return new DynamicalClassLoader().defineClassMy(nameOfDynamicalClass, classBytes);
		} else {
			//...sonst ;)
			return super.resolveClass(desc);
		}
	}

}
